package com.woniu.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.PatientSurgery;
import com.woniu.mapper.PatientSurgeryMapper;
import com.woniu.publisher.SurgeryPublisher;
import com.woniu.service.PatientSurgeryService;
import com.woniu.utils.ResponseEnum;
import com.woniu.utils.ResponseUtil;
import com.woniu.vo.PatientSurgeryVO;
import com.woniu.vo.StaffVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PatientSurgeryServiceImpl implements PatientSurgeryService {
    @Resource
    private PatientSurgeryMapper patientSurgeryMapper;
    @Resource
    private SurgeryPublisher surgeryPublisher;
    @Override
    public ResponseUtil findAll(Integer pageNum, Integer pageSize) {
        try {
            // 先同步数据
            this.syncFromSurgeryApplication();
        } catch (Exception e) {
            log.warn("同步数据失败，继续查询:", e);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<PatientSurgeryVO> surgeryList = patientSurgeryMapper.findAll();
        PageInfo<PatientSurgeryVO> pageInfo = new PageInfo<>(surgeryList);
        return ResponseUtil.get(ResponseEnum.OK, pageInfo);
    }

    @Override
    public ResponseUtil selectByCondition(String patientName, String doctorName, Integer status,
                                          Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PatientSurgeryVO> surgeryList = patientSurgeryMapper.selectByConditionVO(patientName, doctorName, status);
        PageInfo<PatientSurgeryVO> pageInfo = new PageInfo<>(surgeryList);
        return ResponseUtil.get(ResponseEnum.OK, pageInfo);
    }

    @Override
    @Transactional
    public ResponseUtil completeSurgery(Integer id) {
        PatientSurgery updateRecord = new PatientSurgery();
        updateRecord.setId(id);
        updateRecord.setStatus(1); // 1-已完成
        updateRecord.setEndTime(new Date()); // 设置手术结束时间

        int rows = patientSurgeryMapper.updateByPrimaryKeySelective(updateRecord);

        if (rows == 1) {
            // 同时更新手术申请表和收费表的状态
//            patientSurgeryMapper.updateSurgeryFeeStatus(id);
            return ResponseUtil.get(ResponseEnum.OK, "手术完成");
        } else {
            return ResponseUtil.get(ResponseEnum.FAIL, "更新失败");
        }
    }

    @Override
    @Transactional
    public void syncFromSurgeryApplication() {
        // 从手术申请同步数据到患者手术表
//        patientSurgeryMapper.syncFromSurgeryApplication();
        try {
            log.info("开始从手术申请同步数据...");

            // 从手术申请同步数据到患者手术表
            patientSurgeryMapper.syncFromSurgeryApplication();

            log.info("数据同步完成，开始发送手术提醒...");

            // 【新增】获取刚同步的等待中手术数据
            List<PatientSurgeryVO> newSurgeries = patientSurgeryMapper.selectByConditionVO(null, null, 0);

            // 为每个新同步的手术发送延迟提醒
            for (PatientSurgeryVO surgery : newSurgeries) {
                sendSurgeryStartReminder(surgery);
            }

            log.info("手术提醒发送完成，共同步{}条记录", newSurgeries.size());

        } catch (Exception e) {
            log.error("同步手术数据失败：", e);
            throw new RuntimeException("同步失败", e);
        }
    }


    private void sendSurgeryStartReminder(PatientSurgeryVO surgery) {
        try {
            // 构造提醒消息
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("surgeryId", surgery.getId());
            messageMap.put("patientName", surgery.getPatientName());
            messageMap.put("surgeryName", surgery.getSurgeryName());
            messageMap.put("doctorName", surgery.getDoctorName());
            messageMap.put("applicationId", surgery.getApplicationId());
            messageMap.put("reminderType", "surgery_start");
            messageMap.put("targetRole", "nurse");
            messageMap.put("message",
                    "【手术提醒】患者 " + surgery.getPatientName() + " 的 " +
                            surgery.getSurgeryName() + " 手术即将开始，主治医生：" +
                            surgery.getDoctorName() + "，请护士做好准备");
            messageMap.put("reminderTime", new Date());

            String jsonMessage = JSON.toJSONString(messageMap);

            // 发送延迟消息（10分钟后提醒）
            surgeryPublisher.sendSurgeryReminder(jsonMessage);

            log.info("已发送手术开始提醒：患者{} - {}", surgery.getPatientName(), surgery.getSurgeryName());

        } catch (Exception e) {
            log.error("发送手术开始提醒失败，手术ID：{}", surgery.getId(), e);
        }
    }

    /**
     * 发送手术完成通知
     */
    private void sendSurgeryCompleteNotification(Integer surgeryId) {
        try {
            // 查询手术详情
            PatientSurgery surgery = patientSurgeryMapper.selectByPrimaryKey(surgeryId);
            if (surgery != null) {
                // 这里可以查询更多详情信息...
                String completeMessage = String.format(
                        "【手术完成通知】手术ID：%s 已完成，请护士进行后续处理",
                        surgeryId
                );

                // 记录日志
                log.info(completeMessage);

                //实时通知护士
            }
        } catch (Exception e) {
            log.error("发送手术完成通知失败", e);
        }
    }

    /**
     * 手动发送手术提醒（用于测试）
     */
    public ResponseUtil sendReminderManually(Integer surgeryId) {
        try {
            // 查询手术信息
            List<PatientSurgeryVO> surgeries = patientSurgeryMapper.selectByConditionVO(null, null, 0);
            if (!surgeries.isEmpty()) {
                // 发送第一个等待中的手术提醒
                sendSurgeryStartReminder(surgeries.get(0));
                return ResponseUtil.get(ResponseEnum.OK, "提醒发送成功");
            }
            return ResponseUtil.get(ResponseEnum.FAIL, "未找到等待中的手术");
        } catch (Exception e) {
            log.error("手动发送提醒失败：", e);
            return ResponseUtil.get(ResponseEnum.FAIL, "发送失败");
        }
    }
}
